<template>
  <el-form ref="deptRuleFormRef" :model="deptRuleForm" label-width="auto" :inline="true">
    <el-form-item label="部门名称" prop="deptName">
      <el-input v-model.trim="deptRuleForm.deptName" placeholder="请输入部门名称" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(deptRuleFormRef)">
        查询
      </el-button>
      <el-button @click="resetForm(deptRuleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  <div>
    <el-button type="primary" @click="handleACreate" v-has="'dept-create'">创建</el-button>
  </div>
  <div>
    <el-table :data="tableData" style="width: 100%" row-key="_id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column :label="item.label" :prop="item.property" v-for="(item, t) in columns" :key="t" />
      {{ tableData }}
      <el-table-column align="center" label="操作" width="200px">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleAdd(scope.row)" v-has="'dept-add'">新增</el-button>
          <el-button size="small" @click="handleEdit(scope.row)" v-has="'dept-edit'">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-has="'dept-delete'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="dialogVisible" :title=dynamicTitle width="35%" draggable @close="closeDialog">
    <div>
      <el-form ref="DialogRuleFormRef" style="max-width: 600px" :model="DialogRuleForm" :rules="rules"
        label-width="auto">
        <el-form-item label="选择部门" prop="deptId">
          <el-cascader :options="options2" :props="props" clearable v-model="DialogRuleForm.deptId"
            :disabled="active == 'edit'" />
          <span>不选择则为一级部门</span>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="DialogRuleForm.deptName" placeholder="请输入您的部门名称" />
        </el-form-item>
        <el-form-item label="员工名称" prop="userName">
          <el-select v-model="DialogRuleForm.userName" clearable placeholder="请输入员工名称" style="width: 240px"
            @change="bindEmail">
            <el-option v-for="item in options" :key="item._id" :label="item.userName"
              :value="`${item.userId}/${item.userName}/${item.userEmail}`" />
          </el-select>
        </el-form-item>
        <el-form-item label="员工邮箱" prop="userEmail">
          <el-input v-model="DialogRuleForm.userEmail" :disabled="true" />
        </el-form-item>

      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="operateForm(DialogRuleFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, computed } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import Api from './../api/index';
import { ElMessage, ElMessageBox } from 'element-plus'

//form
const deptRuleFormRef = ref<FormInstance>()
const deptRuleForm = reactive<RuleForm>({
  deptName: '',
})
//查询
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((vaild) => {
    if (vaild)
      getDeptList()
  })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// user操作按钮
const dialogVisible = ref(false)
const active = ref('create')
//创建
const handleACreate = () => {
  dialogVisible.value = true
  active.value = 'create'
  // 重置表单
  Object.assign(DialogRuleForm, initialDialogForm);
}

//新增
const handleAdd = (row: any) => {
  console.log(row)
  active.value = 'add'
  DialogRuleForm.deptId = row._id
  dialogVisible.value = true
}


//计算动态标题
const dynamicTitle = computed(() => {
  if (active.value == 'create') {
    return '创建菜单'
  } else if (active.value == 'edit') {
    return '编辑菜单'
  } else {
    return ''
  }
})
// 绑定邮箱
const bindEmail = (val: String) => {
  //解构，转成数组
  const [userId, userName, userEmail] = val.split('/')
  //再与DialogRuleForm合并
  Object.assign(DialogRuleForm, { userId, userName, userEmail });
}

//编辑
const handleEdit = (row: User) => {
  console.log(row)
  active.value = 'edit'
  // 这里需要用异步处理一下，避免bug
  nextTick(() => {
    // 把数据整合，使点击编辑可以拿到该数据
    Object.assign(DialogRuleForm, row)
  })
  dialogVisible.value = true
}
//单个删除处理
const handleDelete = (row: any) => {
  console.log(row)
  ElMessageBox.confirm(
    '你确定要删除这个数据吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Api.getDeptDeleteListAPI({ _id: row._id }).then((res) => {
        if (res) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
      })
      getDeptList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}
//关闭表单重置表单信息
const closeDialog = () => {
  if (DialogRuleFormRef.value) {
    DialogRuleFormRef.value.resetFields();
  }
  // 关键：完全重置表单数据
  Object.assign(DialogRuleForm, initialDialogForm);
};
const tableData = ref<User[]>([])

//表单的table中的columns
const columns = [
  {
    label: '部门名称',
    property: 'deptName'
  },
  {
    label: '负责人',
    property: 'userName'
  },
  {
    label: '员工邮箱',
    property: 'userEmail'
  },
  {
    label: '更新时间',
    property: 'updateTime'
  },

  {
    label: '注册时间',
    property: 'createTime'
  }
]

//员工名称下拉框

const options = ref<UserOption[]>([])

// 定义表单数据类型
const DialogRuleFormRef = ref<FormInstance>()
// 1. 定义初始表单数据常量
const initialDialogForm: DialogdeptRuleForm = {
  deptId: [],
  deptName: '',
  userName: '',
  userEmail: '',
};

// 2. 修改表单数据声明
const DialogRuleForm = reactive<DialogdeptRuleForm>({ ...initialDialogForm });
//表单的新增或编辑，连接后端
// 表单的新增或编辑，连接后端
const operateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let params: any = DialogRuleForm;
      params.active = active.value;
      // console.log(params);
      if (active.value == 'create' || active.value == 'add') {
        delete params._id;
      }
      Api.getDeptOperateListAPI(params).then(res => {
        console.log('resdept', res);
        if (res) {
          dialogVisible.value = false
          ElMessage({
            type: 'success',
            message: '设置成功',
          })
          getDeptList()
        }
      })


    } else {
      console.log('error submit!', fields)
    }
  })
};
//表单验证规则
const rules = reactive<FormRules<DialogdeptRuleForm>>({
  deptName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '用户名长度为2-10之间', trigger: 'blur' },
  ],

})

//菜单联级选择
const props = {
  checkStrictly: true,
  label: 'deptName',
  value: '_id'
}
const options2 = ref([])
//请求
//用户数据请求
const getUsersList = async () => {
  const params: any = {}
  params.type = 'dept'
  params.state = 1
  const res: any = await Api.getUsersListAPI(params);
  console.log("resssssssssss", res);
  options.value = res
  console.log("options.value", options.value);

}


const getDeptList = () => {
  Api.getDeptListAPI(deptRuleForm).then((res: any) => {
    console.log(res);
    tableData.value = res
    options2.value = res
    console.log("options2.value", options2.value);

  })
}



onMounted(() => {
  getDeptList()
  getUsersList()
})
</script>

<style>
.el-select__input-wrapper.is-hidden {
  position: initial;
}
</style>
